using B.S.NewMedical.Api.Write.Application.Command.ContentManagement.Carousel;
using B.S.NewMedical.Domain.Hospital;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Write.Application.Handler.ContentManagement.Carousel
{
    /// <summary>
    /// 批量删除轮播图命令处理器
    /// </summary>
    public class DeleteCarouselCommandHandler : IRequestHandler<DeleteCarouselCommand, BatchDeleteResult>
    {
        private readonly IBaseRepository<CarouselModel> _carouselRepository;

        public DeleteCarouselCommandHandler(IBaseRepository<CarouselModel> carouselRepository)
        {
            _carouselRepository = carouselRepository ?? throw new ArgumentNullException(nameof(carouselRepository));
        }

        /// <summary>
        /// 处理批量删除轮播图命令
        /// </summary>
        /// <param name="request">批量删除轮播图命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>批量删除结果</returns>
        public async Task<BatchDeleteResult> Handle(DeleteCarouselCommand request, CancellationToken cancellationToken)
        {
            var result = new BatchDeleteResult();
            var failedIds = new List<int>();
            var successCount = 0;

            try
            {
                // 去重ID列表
                var uniqueIds = request.Ids.Distinct().ToList();

                // 查找所有要删除的轮播图
                var carouselsToDelete = await _carouselRepository.GetAll()
                    .Where(c => uniqueIds.Contains(c.Id) && !c.IsDeleted)
                    .ToListAsync(cancellationToken);

                var foundIds = carouselsToDelete.Select(c => c.Id).ToList();
                var notFoundIds = uniqueIds.Except(foundIds).ToList();

                // 记录未找到的ID
                failedIds.AddRange(notFoundIds);

                // 批量软删除找到的轮播图
                foreach (var carousel in carouselsToDelete)
                {
                    try
                    {
                        carousel.IsDeleted = true;
                        carousel.UpdatePeople = request.UpdatePeople;
                        carousel.UpdateTime = DateTime.Now;

                        await _carouselRepository.UpdateAsync(carousel);
                        successCount++;
                    }
                    catch (Exception)
                    {
                        failedIds.Add(carousel.Id);
                    }
                }

                result.SuccessCount = successCount;
                result.FailCount = failedIds.Count;
                result.FailedIds = failedIds;
                result.Success = successCount > 0;

                if (result.FailCount > 0)
                {
                    result.Message = $"批量删除完成，成功 {successCount} 个，失败 {result.FailCount} 个";
                }
                else if (successCount > 0)
                {
                    result.Message = $"批量删除成功，共删除 {successCount} 个轮播图";
                }
                else
                {
                    result.Message = "没有找到可删除的轮播图";
                }

                return result;
            }
            catch (Exception ex)
            {
                // 发生异常时，所有操作都视为失败
                result.Success = false;
                result.SuccessCount = 0;
                result.FailCount = request.Ids.Count;
                result.FailedIds = request.Ids.Distinct().ToList();
                result.Message = $"批量删除失败：{ex.Message}";

                return result;
            }
        }
    }
}